const express = require('express')
const morgan = require('morgan')
const cors = require('cors')

const tokenMiddleware = require('./middleware/tokenMiddleware')
const AdminController = require('./controller/AdminController')
const ArticleController = require('./controller/ArticleController')
const router = require('./router/admin.router')
const { PORT } = require('./config/index')

const app = express()

const sequelize = require('./config/init-sequelize')
const db = require('./config/init-table-model.js')

// 普通中间件，挂载操作数据对象db
app.use((req, res, next) => {
  db.sequelize = sequelize
  req.db = db
  next()
})

// 跨域
app.use(cors())

// http请求日志中间件
app.use(morgan('tiny'))

// 设置静态资源
app.use('/uploads/', express.static('./uploads/'))

// 解析表单请求体 application/x-www-form-urlencoded，extended: true 允许包含任何数据类型
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

// 应用级中间件：统一校验token。任何请求路径只要是/api打头,都会经过下面的中间件
app.use('/api', tokenMiddleware)

// 后台登录接口
app.post('/admin/login', AdminController.login)

// 刷新token
app.post('/admin/refreshToken', AdminController.refreshToken)

// 无论何种请求方式，只要路由以/api/admin开头，就会执行router中间件
app.use('/api/admin', router)

app.get('/admin/logo', AdminController.logoInfo)

// TODO: 附件：获取upload目录中所有图片资源
app.get('/admin/getImages', ArticleController.getImages)

// TODO: 删除指定图片文件
app.get('/admin/delImages', ArticleController.delImages)

// 错误中间件,如参数错误，或sql执行错误
app.use((err, req, res, next) => {
  res.json({ code: '00100', msg: err.message, data: {} })
})

app.listen(PORT, () => {
  console.log(`server is running at port ${PORT}`)
})
